import { export2Excel } from 'export2excel/lib/index'
import { MessageBox } from 'element-ui'
import Ajax from './ajax'
// 数据导出
const formatDate = function (time) {
  let date = new Date(time * 1000)
  let Y = date.getFullYear() + '-'
  let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-'
  let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
  let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return Y + M + D + h + m + s
}
const alert = function (msg, type) {
  if (!type) type = 'info'
  MessageBox.alert(msg, { type: type })
}
const exportPlayers = function (code) {
  if (!code) {
    Vue.$alert('参数错误')
    return
  }
  Ajax.get('activity/export/players/' + code)
    .then(res => {
      if (res.code == 0) {
        var data = res.data
        var header = [
          { title: '选手编号', key: 'serial' },
          { title: '选手名称', key: 'name' },
          { title: '分组信息', key: 'group' },
          { title: '选手电话', key: 'phone' },
          { title: '选手票数', key: 'ticket' },
          { title: '选手浏览量', key: 'pageView' },
          { title: '选手简介', key: 'info' },
          { title: '添加时间', key: 'addtime' }
        ]
        if (data) {
          for (var i in data) {
            var item = data[i]
            item.addtime = formatDate(item.addtime)
          }
        }

        if (data.length > 0 && data[0].items && data[0].items.length > 0) {
          for (var i in data[0].items) {
            var item = data[0].items[i]
            header.push({ title: item.name, key: 'cus_item_' + i })
          }
          for (var i in data) {
            var item = data[i]
            for (var j in item.items) {
              var sub = item.items[j]
              data[i]['cus_item_' + j] = sub.value
            }
          }
        }

        var xls = [
          {
            columns: header,
            data: data
          }
        ]
        export2Excel('选手数据.xlsx', xls)
        alert('数据导出成功', 'success')
      } else {
        alert('获取数据失败:' + res.msg, 'error')
      }
    })
    .catch(err => {
      console.error(err)
      alert('获取数据失败', 'error')
    })
}

export default {
  exportPlayers: exportPlayers
}
